### all buildable modules
modules 				:= $(wildcard */*/*/Makefile) $(wildcard */*/Makefile)
goModules 				:= $(wildcard */*/*/go.mod) $(wildcard */*/go.mod)
forked-sources 			:= $(dir $(wildcard ./src/pkg/forked-libs/*/*/*/*.go))
shared-sources 			:= $(dir $(wildcard ./src/pkg/libs/*/*.go) $(wildcard ./src/pkg/libs/*/*/*.go) $(wildcard ./src/pkg/libs/*/*/*/*.go))
generated-sources 		:= $(dir $(wildcard ./*/*/target/generated-sources/*.go))
executable-sources 		:= $(dir $(wildcard ./*/*/cmd/*.go))

### common variables
buildDir 		:= ./target
codegenBinary 	:= ${GOPATH}/bin/oapi-codegen
licensesBinary	:= ${GOPATH}/bin/go-licenses
workspaceMode 	:= true
registry 		:=
buildVersion 	:= $(shell date -u +"%Y-%m-%dT%H-%M-%SZ")

# making accessible to sub makefiles
export buildDir
export codegenBinary
export workspaceMode
export buildVersion
export registry

### codegen variables
codegenVersion 		:= v1.9.1
codegenRepository 	:= github.com/deepmap/oapi-codegen/cmd/oapi-codegen@$(codegenVersion)

### testsum variables
testsumVersion 		:= latest
testsumRepository 	:= gotest.tools/gotestsum@$(testsumVersion)

### licenses variables
licensesVersion 				:= latest
licensesRepository 				:= github.com/google/go-licenses@$(licensesVersion)
licensesCsvFile 				:= $(buildDir)/licenses.csv
ignoredModulesPrefixes 			:= v8s,github.com/hashicorp/go-uuid
licensesSources 				:= $(sort $(forked-sources) $(shared-sources) $(generated-sources) $(executable-sources))
nonProductionSourcesFilters 	:= ./_dev% ./pkg/libs/test%
productionSources 				:= $(filter-out $(nonProductionSourcesFilters),$(licensesSources))

install-generator:
	$(info installing generator version - $(codegenVersion))
	@go install $(codegenRepository)

install-licenses:
	@go install $(licensesRepository)

install-testsum:
	@go install $(testsumRepository)

clean:
	$(info cleaning all modules)
	@$(foreach module,$(modules),$(MAKE) -C $(subst /Makefile,,$(module)) clean &&) true

generate-sources: clean install-generator install-testsum
	$(info generating sources in all modules)
	@$(foreach module,$(modules),$(MAKE) -C $(subst /Makefile,,$(module)) generate-sources &&) true

build: generate-sources
	$(info building all modules)
	@$(foreach module,$(modules),$(MAKE) -C $(subst /Makefile,,$(module)) build &&) true

test:
	$(info testing all modules)
	@$(foreach module,$(modules),$(MAKE) -C $(subst /Makefile,,$(module)) test &&) true

integration-test:
	$(info integration testing all modules)
	@$(foreach module,$(modules),$(MAKE) -C $(subst /Makefile,,$(module)) integration-test &&) true

release: build
	$(info releasing all modules)
	@$(foreach module,$(modules),$(MAKE) -C $(subst /Makefile,,$(module)) release &&) true

get-dependency-licenses: install-licenses generate-sources
	mkdir -p $(buildDir) && $(licensesBinary) csv --ignore $(ignoredModulesPrefixes) $(foreach source,$(productionSources),$(source)) > $(licensesCsvFile)